<template>
  <div class="product-details">
    <div class="product-info">
      <!-- 使用 Element UI 的 el-image 组件 -->
      <el-image :src="product.url" fit="cover" alt="Product Image"></el-image>
      <h2>{{ product.name }}</h2>
      <p>{{ product.description }}</p>
      <p class="price">{{ product.price }}</p>
    </div>
    <div class="comments-section">
      <h3>评论:</h3>
      <el-form @submit.prevent="addComment">
        <el-input
          type="textarea"
          v-model="newComment"
          placeholder="写下你的评论..."
        ></el-input>
        <el-button type="primary" native-type="submit">提交评论</el-button>
      </el-form>
      <!-- 评论迭代，现在使用的是独立的 comments 响应式引用 -->
      <div class="comment" v-for="comment in comments" :key="comment.id">
        <!-- 假设你的评论对象已经包含 avatar 属性 -->
        <el-image
          class="avatar"
          :src="comment.avatarUrl"
          fit="cover"
          alt="Avatar"
        ></el-image>
        <div class="comment-content">
          <p class="user-name">{{ comment.nickName }}</p>
          <p>{{ comment.content }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import * as commentapi from "@/api/comment";
const route = useRoute();
const store = useStore();
const product = ref(route.query);

const comments = ref([]);
const getComments = async () => {
  const { data } = await commentapi.getAllList({
    userId: store.state.userInfo.userId,
  });
  comments.value = data
    .map((i) => ({ ...i, ...i.discuss, ...i.userVo }))
    .filter((i) => +i.targetId === +product.value.flowerId);
};
getComments();
const newComment = ref("");
const addComment = async () => {
  if (newComment.value) {
    const { data } = await commentapi.addItem({
      targetId: product.value.flowerId,
      content: newComment.value,
      userId: store.state.userInfo.userId,
    });
    if (data) {
      newComment.value = "";
      getComments();
    } else {
      ElMessage.warning("评论失败");
    }
  } else {
    ElMessage.warning("输入不能为空");
  }
};
</script>
<style scoped>
.product-details {
  max-width: 800px;
  margin: auto;
  padding: 20px;
}

.product-info img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin-bottom: 20px;
}

.price {
  color: #ff4d4f;
  font-size: 24px;
}

.comments-section {
  margin-top: 40px;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment {
  display: flex;
  align-items: flex-start;
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.comment-content {
  flex: 1;
}

.user-name {
  margin: 0;
  font-weight: bold;
}
.avatar {
  /* 图片样式现应用于 el-image 组件 */
  border-radius: 50%;
  margin-right: 10px;
  /* Element UI 的 el-image 组件添加了额外的包装元素，你可能需要调整以下样式以匹配你的设计 */
  overflow: hidden;
}
</style>